<template>
  <div class="login">
    <el-form
      :model="loginuser"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginuser.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginuser.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('loginuser')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { userlogin } from "../require/api";
export default {
  data() {
    return {
      loginuser: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 5, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
      },
    };
  },

  methods: {
    //登录
    submitForm() {
      this.$refs.ruleForm.validate((val) => {
        // 验证信息
        if (val) {
          //请求登录
          userlogin(this.loginuser).then((res) => {
            console.log(res, "登录");
            if (res.code == 200) {
              this.$message({
                message: "恭喜你，登陆成功",
                type: "success",
              });
              // 存储到本地
              this.$store.dispatch("changeUserAction", res.list);
              //成功==跳转
              this.$router.push("/index");
              // console.log("准备跳转");
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          // console.log("粗错啦");
          this.$message.error("请填写必要信息");
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.login {
  width: 600px;
  height: 500px;
  margin: 120px auto;
}
// .el-form-item {
//   vertical-align: center;
// }
button {
  margin-top: 20px;
}
</style>

